<script setup lang="ts">
import { ref, computed } from 'vue' // 引入 computed
import { useAuth } from '~/composables/auth/useAuth' // 确认路径正确
import { navigateTo } from '#app' // Nuxt 3 导航

definePageMeta({
  layout: 'auth' // 假设有一个用于认证页面的布局
})

const { login, loading, error } = useAuth() // 从 useAuth 获取状态和方法

const account = ref('') // 可以是用户名、邮箱或手机号
const password = ref('')
const accountError = ref('')
const passwordError = ref('')

// 账号验证逻辑
const validateAccount = () => {
  const value = account.value
  const emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!value) {
    accountError.value = '请输入账号'
    return false
  } else if (!emailRegex.test(value) && !phoneRegex.test(value)) {
    accountError.value = '请输入有效的邮箱或手机号'
    return false
  } else {
    accountError.value = ''
    return true
  }
}

// 密码验证逻辑
const validatePassword = () => {
  const value = password.value
  if (!value) {
    passwordError.value = '请输入密码'
    return false
  } else if (value.length < 6) { // 示例：密码至少6位
    passwordError.value = '密码长度不能少于6位'
    return false
  } else {
    passwordError.value = ''
    return true
  }
}

// 计算属性，判断表单是否有效
const isFormValid = computed(() => {
  // 首次加载时不校验，或者当字段有值时校验
  const isAccountPotentiallyValid = !accountError.value || account.value === ''
  const isPasswordPotentiallyValid = !passwordError.value || password.value === ''
  // 确保字段非空且通过验证
  return account.value !== '' && password.value !== '' && isAccountPotentiallyValid && isPasswordPotentiallyValid
})

// 更新登录处理逻辑
const handleLogin = async () => {
  // 先进行一次最终验证
  const isAccountValid = validateAccount()
  const isPasswordValid = validatePassword()

  if (!isAccountValid || !isPasswordValid) {
    return // 验证失败，不提交
  }

  const success = await login(account.value, password.value)
  if (success) {
    navigateTo('/chat') // 修改跳转目标为聊天室
  } // 错误信息已在 useAuth 中处理，并通过 error ref 暴露
}
</script>

<template>
  <div class="login-page">
    <form @submit.prevent="handleLogin" class="space-y-4">
      <h2 class="text-2xl font-semibold text-center mb-6">登录 HmChat</h2>

      <div>
        <label for="account" class="block text-sm font-medium text-gray-700">账号</label>
        <input
          id="account"
          v-model="account"
          @blur="validateAccount" // 失去焦点时验证
          type="text"
          required
          placeholder="邮箱或手机号"
          class="mt-1 block w-full px-3 py-2 border rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
          :class="{'border-red-500': accountError}"
        />
        <p v-if="accountError" class="mt-1 text-xs text-red-600">{{ accountError }}</p>
      </div>

      <div>
        <label for="password" class="block text-sm font-medium text-gray-700">密码</label>
        <input
          id="password"
          v-model="password"
          @blur="validatePassword" // 失去焦点时验证
          type="password"
          required
          placeholder="请输入密码"
          class="mt-1 block w-full px-3 py-2 border rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
          :class="{'border-red-500': passwordError}"
        />
        <p v-if="passwordError" class="mt-1 text-xs text-red-600">{{ passwordError }}</p>
      </div>

      <!-- 显示来自 useAuth 的通用错误信息 -->
      <p v-if="error" class="text-sm text-red-600 text-center">{{ error }}</p>

      <button
        type="submit"
        :disabled="loading || !isFormValid" // 根据加载状态和表单有效性禁用按钮
        class="w-full px-4 py-2 font-medium text-white bg-blue-600 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200 ease-in-out flex items-center justify-center space-x-2"
      >
        <svg
          v-if="loading"
          class="w-5 h-5 animate-spin text-white"
          xmlns="http://www.w3.org/2000/svg"
          fill="none"
          viewBox="0 0 24 24"
        >
          <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
          <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
        </svg>
        <span>{{ loading ? '登录中...' : '登录' }}</span>
      </button>
    </form>
  </div>
</template>

<style scoped>
.login-page {
  /* display: flex; */
  /* flex-direction: column; */
  /* align-items: center; */
  /* justify-content: center; */
  /* min-height: 100vh; */ /* Layout handles centering and min-height */
  /* padding: 2rem; */ /* Removed, layout/form padding should suffice */
  /* background-color: #f3f4f6; */ /* Layout already has bg-gray-100 */
}

form {
  background: white;
  padding: 2rem;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px; /* 限制最大宽度 */
}

/* 移除旧的 button 样式，Tailwind 已处理 */
</style>